/**
 * Created by Administrator on 2017/10/17.
 */
var mongoose = require("mongoose");
var multer  = require('multer'); 
var path = require('path');
var DataCollection = require("../models/upload.model");
var fs = require('fs');
const async = require("async");


//设置存储位置----实例化diskStorage
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads')
  },
  filename: function (req, file, cb) {
  	//返回一个文件名，现在名字avatar+时间戳+源文件名后缀
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
  }
})


//上传保存
exports.upload = function (req,res,next) {
	//实例化 multer
	var upload = multer({
		storage:storage,
	}).single('avatar');

	upload(req,res,(err)=>{
		console.log(req)
			req.file.cateId = req.params.cate;
			const dataColl = new DataCollection(req.file);
			dataColl.save().then(data=>{
				res.json(data)
			})
			res.end("File is upload")

		
	})
}

//分页查询
exports.list = function (req,res,next) {
	// console.log(req.body)
	var page = req.body.page ? req.body.page : 1;
	var rows = req.body.rows ? req.body.rows : 10;
	var queryCondition = {};
    if(req.body._id && req.body._id.length>0){
        queryCondition = {
            cateId:{$in:req.body._id.split(",")}
		};
	}
	if(req.body.title && req.body.title.trim().length>0){
		title = req.body.title,
		queryCondition = {
			"title":new RegExp(title,'i'),
		}
	}
	if(req.body.filename && req.body.filename.trim().length>0){
		filename = req.body.filename,
		queryCondition = {
			"filename":new RegExp(filename,'i'),
		}
	}
	// console.log(queryCondition);
	DataCollection.paginate(queryCondition, {sort:{_id:-1},page: parseInt(page), limit: parseInt(rows)}, (err, result)=>{
		result.rows = result.docs;
		delete result.docs;
		res.json(result)
	});
}

//删除多个删除
exports.removes = function (req,res,next) {
	var ids = req.body.ids;
	if(ids.length>0){
		DataCollection.find({_id:{$in:ids.split(",")}}, (err, result)=>{
			if(err){
				res.json("error 404")
			}

			for(var i=0;i<result.length;i++){
				var psth = `${result[i].destination}/${result[i].filename}`;
				fs.unlink(psth,(err)=>{
					if(err){
						throw err;
					};
				})
			}
			// res.json(123);
			DataCollection.remove({_id:{$in:ids.split(",")}}).then((err,data)=>{
				res.json({"msg":"deletes success","status":200})
			});
		});

	}else{
		res.json({"msg":"deletes fail","status":404})
	}
}